package com.zecan.blog.config;

import com.zaxxer.hikari.HikariDataSource;
import org.quartz.*;
import org.quartz.ee.servlet.QuartzInitializerListener;
import org.springframework.boot.autoconfigure.quartz.QuartzDataSource;
import org.springframework.boot.autoconfigure.quartz.SchedulerFactoryBeanCustomizer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.quartz.SchedulerFactoryBean;

import javax.sql.DataSource;
import java.io.IOException;

@Configuration
public class QuartzConfig implements SchedulerFactoryBeanCustomizer {


  @Bean
  @QuartzDataSource
  public DataSource quartzDataSource() {
    HikariDataSource ds = new HikariDataSource();
    ds.setDriverClassName("com.mysql.cj.jdbc.Driver");
//    连接远程之后会出现直接连接到远程的服务器地址
    ds.setJdbcUrl("jdbc:mysql://localhost:3306/blog?useUnicode=true&characterEncoding=utf8&serverTimezone=Asia/Shanghai");
    ds.setUsername("root");
    ds.setPassword("1234");
    return ds;
  }



  @Bean
  public SchedulerFactoryBean schedulerFactoryBean() throws IOException {
    SchedulerFactoryBean schedulerFactoryBean = new SchedulerFactoryBean();
    schedulerFactoryBean.setDataSource(quartzDataSource());
    return schedulerFactoryBean;
  }

  /*
   * quartz初始化监听器
   */
  @Bean
  public QuartzInitializerListener executorListener() {
    return new QuartzInitializerListener();
  }

  /*
   * 通过SchedulerFactoryBean获取Scheduler的实例
   */
  @Bean
  public Scheduler scheduler() throws IOException {
    return schedulerFactoryBean().getScheduler();
  }

  @Override
  public void customize( SchedulerFactoryBean schedulerFactoryBean) {
    schedulerFactoryBean.setStartupDelay(2);
    schedulerFactoryBean.setAutoStartup(true);
    schedulerFactoryBean.setOverwriteExistingJobs(true);
  }


}
